package com.zhima.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhima.constant.QuestionRedisConstant;
import com.zhima.entity.OjLabel;
import com.zhima.exception.ZhimaOjException;
import com.zhima.mapper.OjLabelMapper;
import com.zhima.service.OjLabelService;
import com.zhima.vo.QuestionLabelVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.zhima.exception.ErrorCode.DUPLICATED_LABEL_NAME;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zhima
 * @since 2023-08-25
 */
@Service
public class OjLabelServiceImpl extends ServiceImpl<OjLabelMapper, OjLabel> implements OjLabelService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public List<QuestionLabelVO> queryAllLabels(Long parentId) {
        if (parentId == 0L) {
            // 先查Redis
            String jsonStr = stringRedisTemplate.opsForValue().get(QuestionRedisConstant.QUESTION_LABEL_ALL);
            // 如果存在并且保存的不为空
            if (jsonStr != null && !jsonStr.isBlank()) {
                return JSONUtil.toList(jsonStr, QuestionLabelVO.class);
            }
        }
        List<QuestionLabelVO> allOjLabels = list().stream().map(this::parseToVo).collect(Collectors.toList());
        Map<Long, QuestionLabelVO> ojLabelsMap = new HashMap<>();
        for (QuestionLabelVO ojLabel : allOjLabels) {
            ojLabelsMap.put(ojLabel.getId(), ojLabel);
        }
        // 虚拟根
        QuestionLabelVO rootOjLabel = new QuestionLabelVO();
        rootOjLabel.setChildrenLabels(new ArrayList<>());
        ojLabelsMap.put(0L, rootOjLabel);
        for (QuestionLabelVO ojLabel : allOjLabels) {
            List<QuestionLabelVO> childrenLabels = ojLabelsMap.get(ojLabel.getParenId()).getChildrenLabels();
            if (childrenLabels == null) {
                ojLabelsMap.get(ojLabel.getParenId()).setChildrenLabels(new ArrayList<>());
            }
            ojLabelsMap.get(ojLabel.getParenId()).getChildrenLabels().add(ojLabel);
        }
        List<QuestionLabelVO> childrenLabels = ojLabelsMap.get(parentId).getChildrenLabels();
        // 只保存最顶级的标签层级信息
        if (parentId == 0L) {
            // 保存到Redis中
            stringRedisTemplate.opsForValue().set(QuestionRedisConstant.QUESTION_LABEL_ALL, JSONUtil.toJsonStr(childrenLabels));
        }
        return childrenLabels;
    }

    @Override
    public boolean createNewLabel(String labelName, Long parentId) {
        stringRedisTemplate.delete(QuestionRedisConstant.QUESTION_LABEL_ALL);
        // 同一个父级标签下，不能有相同标签
        if (lambdaQuery().eq(OjLabel::getName, labelName).eq(OjLabel::getParentId, parentId).count() > 0) {
            throw new ZhimaOjException(DUPLICATED_LABEL_NAME);
        }
        OjLabel ojLabel = new OjLabel();
        ojLabel.setName(labelName);
        ojLabel.setParentId(parentId);
        // 保存
        return save(ojLabel);
    }

    @Override
    public boolean deleteLabelById(Long labelId) {
        stringRedisTemplate.delete(QuestionRedisConstant.QUESTION_LABEL_ALL);
        return removeById(labelId);
    }

    @Override
    public boolean updateLabel(OjLabel ojLabel) {
        stringRedisTemplate.delete(QuestionRedisConstant.QUESTION_LABEL_ALL);
        return updateById(ojLabel);
    }

    private QuestionLabelVO parseToVo(OjLabel ojLabel) {
        return new QuestionLabelVO(
                ojLabel.getId(),
                ojLabel.getName(),
                ojLabel.getParentId(),
                null
        );
    }
}
